﻿using System;
using System.Windows.Forms;
using Assist;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using YArchitech.Controls;
using YArchitech.Revit;

namespace YArchitech.HVAC
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class ConnectRadiatorBath : HYNoTranExternalCommand
	{
		public override Result HYExecute()
		{
			Result result;
			try
			{
				this.tran = new Transaction(base.Doc, "连接散热器");
				this.tran.Start();
				FrmConnRadiator frmConnRadiator = new FrmConnRadiator(base.Doc);
				if (frmConnRadiator.ShowDialog() == DialogResult.OK)
				{
					RadiatorConnHelper radiatorConnHelper = new RadiatorConnHelper(base.Doc, base.Sel);
					radiatorConnHelper.ConnStyle = frmConnRadiator.GetConnStyle();
					radiatorConnHelper.SymbolSupply = frmConnRadiator.GetSupplyAccessory();
					radiatorConnHelper.SymbolReturn = frmConnRadiator.GetReturnAccessory();
					radiatorConnHelper.DistanceSupply = (double)frmConnRadiator.GetSupplyLength();
					radiatorConnHelper.DistanceReturn = (double)frmConnRadiator.GetReturnLength();
					for (;;)
					{
						SubTransaction subTransaction = new SubTransaction(base.Doc);
						try
						{
							radiatorConnHelper.SelectElementSet();
							subTransaction.Start();
							XYZ basePoint = radiatorConnHelper.GetBasePoint();
							if (!radiatorConnHelper.ConnectRadiatorSet(basePoint))
							{
								YJKMessageBox.Information(radiatorConnHelper.Message);
								subTransaction.RollBack();
							}
							else
							{
								subTransaction.Commit();
							}
							RevitVersionFuncs.ClearSelection(base.Sel);
							continue;
						}
						catch (Autodesk.Revit.Exceptions.OperationCanceledException)
						{
							return Autodesk.Revit.UI.Result.Succeeded;
						}
						catch (Exception ex)
						{
							YJKMessageBox.Error(ex.Message);
							subTransaction.RollBack();
							continue;
						}
						break;
					}
				}
				frmConnRadiator.Close();
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Exception ex2)
			{
				YJKMessageBox.Error(ex2.Message);
				result = Autodesk.Revit.UI.Result.Failed;
			}
			finally
			{
				if (this.tran != null)
				{
					TransactionStatus status = this.tran.GetStatus();
					if (status == (TransactionStatus)1)
					{
						this.tran.Commit();
					}
					else if (status == (TransactionStatus)5)
					{
						this.tran.RollBack();
					}
				}
			}
			return result;
		}

		private Transaction tran;
	}
}
